
import { reactive, ref } from "vue";

import type DocumentEditor from './Document.ts'


class JSONHistory {
    Parent: DocumentEditor
    constructor(Parent: DocumentEditor) {
        this.Parent = Parent;
    }
    Records = reactive([])
    RecordsIndex = ref(0)
    // 每次数据更新时,向列表添加记录
    // 由于使用的是JSON 字符串, 相当于每次操作都重新刷新了一遍页面元素
    // 可能产生效率问题,待修复
    SetData(Data) {
        // 防止重做或者退回时,产生死循环
        const _Data = JSON.stringify(Data);
        if (_Data == this.Records[this.RecordsIndex.value]) {
            return;
        }
        // 当历史记录退回到中间时,有新的操作记录被插入,则删除当前历史记录之后的条目
        if (this.RecordsIndex.value != this.Records.length - 1) {
            this.Records.splice(this.RecordsIndex.value, this.Records.length - this.RecordsIndex.value + 1)
        }
        this.Records.push(_Data);
        if (this.Records.length > 20) {
            this.Records.shift();
        };
        this.RecordsIndex.value = this.Records.length - 1;
    }
    // 退回
    Undo() {
        const index = this.RecordsIndex.value - 1;
        if (this.Records[index]) {
            this.RecordsIndex.value -= 1;
            this.Parent.SetData(JSON.parse(this.Records[index]))
            this.Parent.ActiveId.value = null;
        }
    }
    // 重做
    Redo() {
        const index = this.RecordsIndex.value + 1;
        if (this.Records[index]) {
            this.RecordsIndex.value += 1;
            this.Parent.SetData(JSON.parse(this.Records[index]))
            this.Parent.ActiveId.value = null;
        }
    }
    destroy() {
        this.Records = null
        this.RecordsIndex = null
    }

}


export default JSONHistory